﻿using MangoMes.Commont.DapperHelps;
using MangoMes.Commont.Domain.Productions;
using MangoMes.Commont.DTOs;
using MangoMes.Commont.Infrastructures.Interfaces;
using MediatR;
using NPOI.OpenXmlFormats.Dml;

namespace MangoMes.Write.API.Applications.Pickinges
{
    public class ProdlineSeachHandler : IRequestHandler<ProdlineSeachCommand, PageDTO<ProdlineDto>>
    {
        #region 仓储
        /// <summary>
        /// 仓储
        /// </summary>
        private readonly IBateRepository<ProdlineDto> ProdlineDtoDtoRepository;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="ProdlineDtoDtoRepository"></param>
        public ProdlineSeachHandler(IBateRepository<ProdlineDto> ProdlineDtoDtoRepository)
        {
            this.ProdlineDtoDtoRepository = ProdlineDtoDtoRepository;
        }

        #endregion

        #region 生产领料单行 列表
        /// <summary>
        /// 生产领料单行 列表
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<PageDTO<ProdlineDto>> Handle(ProdlineSeachCommand request, CancellationToken cancellationToken)
        {
            //异常处理
            try
            {
                //初始化一个ResultDTO<ProdlineDto>对象result，并设置Code为 0
                PageDTO<ProdlineDto> result = new PageDTO<ProdlineDto>();

                var pageNum = (request.pageIndex - 1) * request.pageSize;
                //创建DapperHelper对象 用于与数据库进行交互
                DapperHelper dapperHelper = new DapperHelper();
                ProdlineDto dto = new ProdlineDto();

                //连接mySql 
                string conn = dapperHelper.MangoMesWrite;

                //sql语句
                //string str = $"select * from stockremoval a join warehouselist b on a.WarehouseId = b.StashId join productmanage c on a.productManageNode=c.productManageNode";
                string str = $"select * from prodline a join productmanage b on a.productManageNode=b.productManageNode join warehouselist c on a.StashId =c.StashId WHERE a.PickingNode='{request.PickingNode}'";

                var list = ProdlineDtoDtoRepository.GetAll(str, dto, conn).ToList();

                result.TotalCount = list.Count(); //计算list列表中元素个数
                result.PageCount = (int)Math.Ceiling((list.Count() * 1.0) / request.pageSize); //表示总的记录数量
                list = list.OrderBy(x => x.ProdLineId).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();
                result.Data = list; //计算总页数

                return result;
            }
            catch (Exception)
            {

                throw;
            }
        }
        #endregion

    }
}
